<?php
/**
 * 
 * @author tangbl
 * 
 */
class UserAction extends CommonAction {
	
	public function _initialize() {
		parent::_initialize();
		parent::_initmenu();	
	}
	
	/**
	 * 列表
	 */
	public function index(){
		
		if(IS_AJAX){
			
			import('ORG.Util.Page');
			$model     = D("User");
			
			$orderDesc = $this->_get("orderDirection","trim","desc");;
			$orderName = $this->_get("orderName","trim","addtime");
			$pageNum   = $this->_get("pageNum","intval",C('web_admin_pagenum'));
			$nowPage   = $this->_get("p","intval",1);
			
			$map       = unescape($this->_get("where"));
			$map       = "1=1 ".$map;
			$count     = $model->where($map)->count();
			$Page      = new Page($count);
			$list      = $model->where($map)->order($orderName.' '.$orderDesc)
						->page($nowPage.','.$pageNum)->select();
			$totalPage = ceil($count/$pageNum);
			C('web_admin_pagenum',$pageNum);
			
			$jsonData  = array('page'=>$nowPage,'total'=>$count,'rows'=>array(),'totalPage'=>$totalPage);
			$status1   = L('usr_form_ele_status_1');
			$status2   = L('usr_form_ele_status_2');
			$sex1      = L('usr_form_ele_sex_1');
			$sex2      = L('usr_form_ele_sex_2');
			$upd       = L('cfg_list_itf_btn_modify');
			$del       = L('cfg_list_itf_btn_delete');
			foreach($list AS $row){
				$sex    = $row['sex'] == 1  ? $sex1 : $sex2;
				$status = $row['status'] == 1 ? $status1 : $status2;
				$del    = $row['username'] == C(SPECIAL_USER) ? "" : "red delAlone";
				$entry = array('id'=>$row['id'],
					'cell'=>array(
						'id'       => $row['id'],
						'username' => $row['username'],
						'role'     => $model->getRoleName($row['role']),
						'realname' => $row['realname'],
						'email'    => $row['email'],
						'phone'    => $row['phone'],
						'status'   => $status,
						'sex'      => $sex,
						'addTime'  => date('Y-m-d',$row['addtime']),
						'deal'=>'
					 <a href="'.__URL__.'/edit/id/'.$row['id'].'" class="btn blue" title="'.$upd.'"><i class="icon-edit"></i></a>
				     <a href="#" class="btn '.$del.'"  data-id="'.$row['id'].'" title="'.$del.'"><i class="icon-remove"></i></a>'
					),
				);
				$jsonData['rows'][] = $entry;
			}
			$this->ajaxReturn($jsonData,'JSON');
			
		}else{
			$this->display();
		}
	}
	
	/**
	 * 添加用户
	 */
	public function add(){
		
		$user  =  D("User");
		if(IS_POST){
			if($user->create()){
				$solevar = $user->solevar;
				$user_id = $user->add();
                if($user_id){
					add_edit_thumb("single",$solevar,"User");
                    $data['user_id'] = $user_id;
                    $data['role_id'] = $this->_post('role');
                    M("RoleUser")->data($data)->add();

                    $this->assign("jumpUrl",U('/User/index'));   
					$this->success(L('cfg_form_tipmsg_addsucc'));
                }
			}else{
				$this->error($user->getError());	
			}
		}else{
			
			$this->assign("lang",getLang());
			
			$roles = $user->getAllRole();
			$html  = "";
			foreach($roles as $v){
				$html .= "<option value='".$v['id']."' outlet='".$v['outlet']."'>".$v['name']."</option>";
			}
			$this->assign("roles",$html); 
			
			//获取地址
			$lang    = getLang();
			$options = getDictByKey("Dict_address",$lang);
			$this->assign("json",$options["array"]);
			
			$this->display();
		}
	}
	
	/**
	 * 修改用户
	 */
	public function edit(){
		$user  =  D("User");
		if(IS_POST){
			if($user->create()){
				$id       = $user->id;
				$role     = $user->role;
				$solevar  = $user->solevar;
				$password = $this->_post("epassword");
				if($password != C("CONFUSE")){//修改密码
					$user->password = myencrypt($password);
				}
				$user->save();//保存用户数据 todo 总是返回false
				
				$data['user_id']  = $id;
				$data['role_id']  = $role;
				$RoleUser         = M("RoleUser");
				$RoleUser->where("user_id=$id and role_id=$role")->delete();//删除用户对应角色 todo
				$RoleUser->data($data)->add();
				
				add_edit_thumb("single",$solevar);
				
				$this->assign("jumpUrl",U('/User/index'));   
				$this->success(L('cfg_form_tipmsg_editsucc'));
			}else{
				$this->error($user->getError());	
			}
		}else{
			
			$id    = $this->_get('id','intval',0);
			$data  = $user->find($id); 
			$this->assign("user",$data);
			
			$roles = $user->getAllRole();
			$html  = "";
			foreach($roles as $v){
				if($data['role'] == $v['id']){
					$html .= "<option selected value='".$v['id']."' outlet='".$v['outlet']."'>".$v['name']."</option>";
				}else{				
					$html .= "<option value='".$v['id']."' outlet='".$v['outlet']."'>".$v['name']."</option>";
				}
			}
			$this->assign("roles",$html); 
			
			//获取地址
			$lang    = getLang();
			$options = getDictByKey("Dict_address",$lang);
			$this->assign("json",$options["array"]);
			
			if($data['area']){
				$dict = D("Dict");
				$row  = $dict->find($data['area']);
				$this->assign("row",$row);
			
				$list = mapByArray($data['area'],"area");
				$this->assign("outlet",$list);
			}
			
			$single = find_thumb($data['solevar'],'single');
			$this->assign("single",$single);
			
			$this->display();
		}
	}
	
	/**
	 * 删除用户
	 */
	public function del(){
		 $id       = $this->_get('id',"intval","0");
		 $User     = M("User");
		 $res1     = $User->delete($id);
		  
		 $RoleUser = M("RoleUser");
		 $where    = "user_id in ($id)";
		 $res2     = $RoleUser->where($where)->delete();
		 if($res1&&$res2){
			  $this->ajaxReturn($res1+$res2,L('cfg_form_tipmsg_delsucc'),1);
		 }else{
			 $this->ajaxReturn(0,L('cfg_form_tipmsg_delfail'),0);
		 }
	}
	
	/**
	 * 角色列表
	 */
	public function role_index(){
		
		if(IS_AJAX){
			
			import('ORG.Util.Page');
			$model     = D("Role");
			
			$orderDesc = $this->_get("orderDirection","trim","desc");;
			$orderName = $this->_get("orderName","trim","addtime");
			$pageNum   = $this->_get("pageNum","intval",C('web_admin_pagenum'));
			$nowPage   = $this->_get("p","intval",1);
			
			$map       = unescape($this->_get("where"));
			$map       = "1=1 ".$map;
			$count     = $model->where($map)->count();
			$Page      = new Page($count);
			$list      = $model->where($map)->order($orderName.' '.$orderDesc)
						->page($nowPage.','.$pageNum)->select();
			$totalPage = ceil($count/$pageNum);
			C('web_admin_pagenum',$pageNum);
			
			$status1   = L('cfg_form_ele_status_1');
			$status2   = L('cfg_form_ele_status_2');
			$outlet1   = L('rle_form_ele_outlet1');
			$outlet2   = L('rle_form_ele_outlet2');
			$permbtn   = L('rle_man_page_title');
			$menubtn   = L('rle_page_backmenu');
			$upd       = L('cfg_list_itf_btn_modify');
			$del       = L('cfg_list_itf_btn_delete');
			$jsonData  = array('page'=>$nowPage,'total'=>$count,'rows'=>array(),'totalPage'=>$totalPage);
			foreach($list AS $row){
				$status = $row['status']==1 ? $status1 : $status2;
				$outlet = $row['outlet']==1 ? $outlet1 : $outlet2;
				$del    = $row['id']==1 ? "" : "red delAlone";
				$entry  = array('id'=>$row['id'],
					'cell'=>array(
						'id'       => $row['id'],
						'name'     => $row['name'],
						'sort'     => $row['sort'],
						'status'   => $status,
						'outlet'   => $outlet,
						'deal'=>'
					  <button type="button" class="btn green"  title="'.$permbtn.'"
					   onclick="setting_access('.$row['id'].',\''.$row['name'].'\')"><i class="icon-group"></i></button>
					  <button type="button" class="btn green"  title="'.$menubtn.'"
					   onclick="setting_menu('.$row['id'].',\''.$row['name'].'\')"><i class="icon-sitemap"></i></button>
					  <a href="'.__URL__.'/role_edit/id/'.$row['id'].'" class="btn blue" title="'.$upd.'"><i class="icon-edit"></i></a>
				      <a href="#" class="btn '.$del.'" data-id="'.$row['id'].'" title="'.$del.'"><i class="icon-remove"></i></a>'
					),
				);
				$jsonData['rows'][] = $entry;
			}
			$this->ajaxReturn($jsonData,'JSON');
			
		}else{
			
			$this->display();
		}
		
	}
	
	/**
	 * 添加角色
	 */
	public function role_add(){
		
		$model  =  D("Role");
		if(IS_POST){
			if($model->create()){
				$model->add();
				$this->assign("jumpUrl",U('User/role_index')); 
                $this->success(L('cfg_form_tipmsg_addsucc'));
			}else{
				$this->error($model->getError());
			}
		}else{
			$this->display();
		}
	}
	
	/**
	 * 修改角色
	 */
	public function role_edit(){
		
		$model  =  D("Role");
		if(IS_POST){
			if($model->create()){				
				$model->save();
				$this->assign("jumpUrl",U('User/role_index'));   
				$this->success(L('cfg_form_tipmsg_editsucc'));
			}else{
				$this->error($model->getError());
			}
		}else{
			$id    = $this->_get('id','intval',0);
			$data  = $model->find($id); 
			$this->assign("role",$data); 
			
			$this->display();
		}
	}
	
	/**
	 * 修改个人资料
	 */
	public function myedit(){
		
		$user  =  D("User");
		if(IS_POST){
			if($user->create()){
				
				$user->id = session(C('USER_AUTH_KEY'));
				$id       = $user->id;
				$role     = $user->role;
				$solevar  = $user->solevar;
				$password = $this->_post("epassword");
				if($password != C("CONFUSE")){
					$user->password = myencrypt($password);
				}
				$user->save();
				add_edit_thumb("single",$solevar,"User");
				
				$expire = C("COOKIE_KEEP_TIME");
				$rows   = $user->find($id);
				$url    = U('Index/index');
				if($rows['skin']){
					cookie('style_color',$rows['skin'],$expire);
					session('skin',$rows['skin']);
				}
				if($rows['lang']){
					cookie('think_language',$rows['lang'],$expire);
					$url = U('Index/index','l='.$rows['lang']);
				}
				//echo $url;exit();
				
				wlog(1,"",$id);
				$this->assign("jumpUrl",$url);   
				$this->success(L('cfg_form_tipmsg_editsucc'));
			}else{
				wlog(2,$user->getError());
				$this->error($user->getError());	
			}
		}else{
			
			$id    = session(C('USER_AUTH_KEY'));
			$data  = $user->find($id); 
			$this->assign("user",$data);
			
			$lang   = create_option_key(C("LANG_ARRAY"),$data['lang']);
			$this->assign("lang",$lang); 
			
			$roles  = $user->getAllRole();
			$html   = create_option_array($roles,'id','name',$data['role']);
			$this->assign("roles",$html); 
			
			$single = find_thumb($data['solevar'],'single');
			$this->assign("single",$single);
			
			$this->display();
		}
	}
	
	//删除角色
	public function role_del(){
		 //删除角色表
		 $id       = $this->_get('id',"intval","0");
		 $Role     = M("Role");
		 $res1     = $Role->delete($id);
		 //删除角色用户表关联表
		 $RoleUser = M("RoleUser");
		 $where    = "role_id = $id";
		 $res2     = $RoleUser->where($where)->delete();
		 //删除角色节点关联表
		 $Aceess   = M("Access");
		 $res3     = $Aceess->where($where)->delete();
		 if($res1){
			  $this->ajaxReturn($res1,L('cfg_form_tipmsg_delsucc'),1);
		 }else{
			 $this->ajaxReturn(0,L('cfg_form_tipmsg_delfail'),0);
		 }
	}
	
	//权限管理
	public function access(){
		if(IS_POST){
			  $roleid = $this->_post('roleid','intval',0);
			  $nodeid = $this->_post('nodeid');
			  if(!$roleid) $this->error(L('cfg_form_tipmsg_illgel'));
			  $AccessDB = D('Access');
			  if (is_array($nodeid) && count($nodeid) > 0) {  //提交得有数据，则修改原权限配置
				  $AccessDB -> delAccess(array('role_id'=>$roleid));  //先删除原用户组的权限配置
	  
				  $NodeDB = D('Node');
				  $node = $NodeDB->getAllNode();
	  
				  foreach ($node as $_v) $node[$_v[id]] = $_v;
				  foreach($nodeid as $k => $node_id){
					  $data[$k] = $AccessDB -> get_nodeinfo($node_id,$node);
					  $data[$k]['role_id'] = $roleid;
				  }
				  $AccessDB->addAll($data);   // 重新创建角色的权限配置
			  } else {    //提交的数据为空，则删除权限配置
				  $AccessDB -> delAccess(array('role_id'=>$roleid));
			  }
			  
			  $AccessDB ->clearRoleCache($roleid);//清除缓存
			  
			  RBAC::getAccessAction();
			  RBAC::getAccessMenu();
			  
			  exit("<script type='text/javascript'>window.parent.location.reload();
				   window.parent.$('.aui_close').click();</script>");
			  //$this->assign("jumpUrl",U('/User/access',array('roleid'=>$roleid)));
			  //$this->success(L('rle_form_setaccess_succ'));
			
		}else{
			$roleid = $this->_get('roleid','intval',0);
			if(!$roleid) $this->error(L('cfg_form_tipmsg_illgel'));
			Vendor('Common.Tree');  //导入通用树型类
	
			$Tree = new Tree();
			$Tree->icon = array('&nbsp;&nbsp;&nbsp;│ ','&nbsp;&nbsp;&nbsp;├─ ','&nbsp;&nbsp;&nbsp;└─ ');
			$Tree->nbsp = '&nbsp;&nbsp;&nbsp;';
	
			$NodeDB = D('Node');
			$node = $NodeDB->getAllNode();
	
			$AccessDB = D('Access');
			$access = $AccessDB->getAllAccess('','role_id,node_id,pid,level');
		   
			$lang     = getLang();
			foreach ($node as $n=>$t) {
				$node[$n]['checked']  = ($AccessDB->is_checked($t,$roleid,$access))? ' checked' : '';
				$node[$n]['depth']    = $AccessDB->get_level($t['id'],$node);
				$node[$n]['pid_node'] = ($t['pid'])? ' class="tr lt child-of-node-'.$t['pid'].' trlevel_'.$node[$n]['depth'].'"' : '';
				$node[$n]['title']    = dejsonByLang($t['langval'],$lang);
			}
			$str  = "<tr id='node-\$id' \$pid_node>
						<td style='padding-left:30px;'>\$spacer<input type='checkbox' name='nodeid[]' value='\$id' class='mycheck' level='\$depth' \$checked onclick='javascript:checknode(this);' > \$title </td>
					</tr>";
	
			$Tree->init($node);
			$html_tree = $Tree->get_tree(0, $str);
			$this->assign('html_tree',$html_tree);
	
			$this->display();
		}
		
	}
	
	/**
	 * 重新生成权限菜单缓存
	 
	public function cache(){
	
		//重新生成权限菜单缓存
		$access = D("Access");
		$role   = D("Role");
		$roles  = $role->getAllRole();
		foreach($roles as $v){
			$access->clearRoleCache($v['id']);
		}
		wlog(1);
		$this->success("生成碎片缓存成功");
	}
	*/
	
	/**
	 * 后台菜单配置
	 */
	public function menu(){
		
		if(IS_POST){
			$roleid = $this->_post('roleid','intval',0);
			$nodeid = $this->_post('nodeid');
			if(empty($roleid)){
				$this->error(L('cfg_form_tipmsg_illgel'));
			}
			$AccessDB = D('MenuAccess');
			if (is_array($nodeid) && count($nodeid) > 0) {
				//先删除原用户组的权限配置
				$AccessDB -> delAccess(array('role_id'=>$roleid));
	
				$NodeDB = D('Menu');
				$node = $NodeDB->getAllNode();
	
				foreach ($node as $_v){
					$node[$_v[id]] = $_v;
				}
				foreach($nodeid as $k => $node_id){
					$data[$k] = $AccessDB -> get_nodeinfo($node_id,$node);
					$data[$k]['role_id'] = $roleid;
				}
				//重新创建角色的权限配置
				$AccessDB->addAll($data);
			} else {    
				//提交的数据为空，则删除权限配置
				$AccessDB -> delAccess(array('role_id'=>$roleid));
			}
				
			$AccessDB ->clearRoleCache($roleid);//清除缓存
			RBAC::getAccessAction();
			RBAC::getAccessMenu();
				
			exit("<script type='text/javascript'>window.parent.location.reload();
				   window.parent.$('.aui_close').click();</script>");
				
		}else{
			
			$roleid = $this->_get('roleid','intval',0);
			if(empty($roleid)){
				$this->error(L('cfg_form_tipmsg_illgel'));
			}
			Vendor('Common.Tree');
	
			$Tree = new Tree();
			$Tree->icon = array('&nbsp;&nbsp;&nbsp;│ ','&nbsp;&nbsp;&nbsp;├─ ','&nbsp;&nbsp;&nbsp;└─ ');
			$Tree->nbsp = '&nbsp;&nbsp;&nbsp;';
	
			$NodeDB = D('Menu');
			$node   = $NodeDB->getAllNode();
	
			$AccessDB = D('MenuAccess');
			$access   = $AccessDB->getAllAccess('','role_id,menu_id,pid,level');
			$lang     = getLang();
			foreach ($node as $n=>$t) {
				$node[$n]['checked']  = ($AccessDB->is_checked($t,$roleid,$access))? ' checked' : '';
				$node[$n]['depth']    =  $AccessDB->get_level($t['id'],$node);
				$node[$n]['pid_node'] = ($t['pid'])? ' class="tr lt child-of-node-'.$t['pid'].' trlevel_'.$node[$n]['depth'].'"' : '';
				$node[$n]['title']    =  dejsonByLang($t['value'],$lang);
				$node[$n]['disabled'] = '' ;
				if($t['level']>1){//todo
					$node[$n]['disabled'] = $AccessDB->isabled($t,$roleid);
				}
				
			}
			$str  = "<tr id='node-\$id' \$pid_node>
						<td style='padding-left:30px;'>\$spacer<input \$disabled type='checkbox' name='nodeid[]' value='\$id' class='mycheck' level='\$depth' \$checked onclick='javascript:checknode(this);' > \$title </td>
					</tr>";
	
			$Tree->init($node);
			$html_tree = $Tree->get_tree(0, $str);
			$this->assign('html_tree',$html_tree);
	
			$this->display();
		}
	}
	
}
?>